﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Diagnostics;

namespace OPENXMLLib
{
    public class DefinedNameResolver
    {
        public static void Resolve(SpreadsheetDocument xDoc)
        {
            IEnumerable<Sheet> sheets = xDoc.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().ToList();
            if (xDoc.WorkbookPart.Workbook.DefinedNames == null)
            {
                return;
            }

            List<DefinedName> defNames = xDoc.WorkbookPart.Workbook.DefinedNames.Elements<DefinedName>().ToList();

            foreach (var defName in defNames)
            {
                bool isValid = false;
                foreach (var sheet in sheets)
                {
                    // 包含 'sheetname'
                    if (defName.InnerText.Contains("'" + sheet.Name + "'"))
                    {
                        isValid = true;
                        break;
                    }
                }

                if (!isValid)
                {
                    Debug.WriteLine(string.Format("已处理DefinedName：({0}){1}", defName.Name, defName.InnerText));
                    // 干掉
                    defName.Remove();
                }
            }
            xDoc.WorkbookPart.Workbook.Save();
        }
    }
}
